package com.train.mgr.modules.biz.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.train.mgr.modules.biz.dto.response.FabeVo;
import com.train.mgr.modules.biz.entity.Lesson;
import com.train.mgr.modules.biz.service.IAliQwenService;
import com.train.mgr.modules.biz.service.ICompletenessService;
import com.train.mgr.modules.biz.utils.PromptTemplates;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/**
 * 完整度
 */
@Slf4j
@RequiredArgsConstructor
@Service("ICompletenessService")
public class CompletenessServiceImpl implements ICompletenessService {

    @Autowired
    private IAliQwenService aliQwenService;


    @Override
    public String getFABEString(Lesson lesson){
        String json = lesson.getSalesLanguage();
        // 2. 使用 Jackson 一键转对象
        try{
            ObjectMapper mapper = new ObjectMapper();
            FabeVo dto = mapper.readValue(json, FabeVo.class);
            String result = new StringBuilder()
                    .append(dto.getF()).append('.')
                    .append(dto.getA()).append('.')
                    .append(dto.getB()).append('.')
                    .append(dto.getE())
                    .toString();
            return result;
        }catch (Exception ex){
            ex.printStackTrace();
            return "";
        }
    }

    /**
     * 完整度得分 = (1 - WER) * 100%
     * @param wer 语音识别词错误率，范围 [0,1]
     * @return 完整度得分，范围 [0,100]，保留 1 位小数
     */
    @Override
    public BigDecimal calCompletenessScore(double wer) {
        // 容错：WER 可能略大于 1 或小于 0
        wer = Math.max(0.0, Math.min(1.0, wer));
        //log.info("******************* wer:{}",wer);
        double score = (1.0 - wer) * 100;
        return BigDecimal.valueOf(score)
                .setScale(1, RoundingMode.HALF_UP);
    }


    @Override
    public String getQwenModelFeedback(String salesLanguage,String audioText){
        String newSalesLanguage = replaceSalesLanguage(salesLanguage);
        String prompt = String.format(PromptTemplates.COMPLETENESS_SCORE,
                                    newSalesLanguage,
                                    audioText);
         log.info("【完整度】文案提示词:{}",prompt);
         return afterMarker(aliQwenService.getQwenFeedBack(prompt));
    }


    private String afterMarker(String raw) {
        if (raw == null) return null;
        final String MARK = "【表现分析与改进建议】";
        int idx = raw.indexOf(MARK);
        // 找不到原样返回；找到则返回标记之后的内容（不含标记）
        return idx < 0 ? raw : raw.substring(idx + MARK.length());
    }


    private String replaceSalesLanguage(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        Map<Character, String> map = new HashMap<>();
        map.put('F', "产品特点");
        map.put('A', "核心优势");
        map.put('B', "客户利益");
        map.put('E', "证据支持");

        StringBuilder sb = new StringBuilder();
        for (char c : input.toCharArray()) {
            sb.append(map.getOrDefault(c, String.valueOf(c)));
        }
        return sb.toString();
    }

}
